package com.org.utils.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import com.org.utils.string.StringUtils;



/**
 * servlet api工具类
 * 
 */
public class ServletUtils {
	
	/***
	 * HttpSession
	 * @return
	 */
	protected static HttpSession getSession(){
		 return getRequest().getSession();
	 }
	
	/**
	 *  设置Session
	 * @param name
	 * @param value
	 */
	public static void setSession(String name, Object value) {
		getSession().setAttribute(name, value);
	}

	/***
	 * getResponse
	 * @return
	 */
	public static HttpServletResponse getResponse(){
		HttpServletResponse response = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse(); 
		return response;
		
	}
	/***
	 * 当前加了上面的listener后也可以使用代码的方式获取reuqest对像
	 * @return
	 */
	public static HttpServletRequest getRequest(){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public static PrintWriter setResponseWriter(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		return out;
	}

	/**
	 * 获得会话对象变量值
	 */
	public static Object getSessionValue(HttpServletRequest request, String key) {
		// 返回值
		Object sessionValue = null;
		// 验证参数
		if (!StringUtils.isEmpty(key)) {
			HttpSession httpSession = request.getSession();
			sessionValue = httpSession.getAttribute(key);
		}
		// 返回结果
		return sessionValue;
	}

	/**
	 * 获得请求对象中的变量值
	 */
	public static String getRequestValue(HttpServletRequest request, String key) {
		// 返回值
		String requestValue = null;
		// 验证参数
		if (StringUtils.isEmpty(key)) {
			requestValue = request.getParameter(key);
		}
		// 返回结果
		return requestValue;
	}
	 

	/**
	 * 获得请求对象中的变量值
	 */
	public static String[] getRequestValues(HttpServletRequest request,
			String key) {
		// 返回值
		String[] requestValues = null;
		// 验证参数
		if (StringUtils.isEmpty(key)) {
			requestValues = request.getParameterValues(key);
		}
		// 返回结果
		return requestValues;
	}
	
 
	/**
	 * 在请求对象中设置属性
	 */
	public static void setRequestValue(HttpServletRequest request, String key, Object value) {
		request.setAttribute(key, value);
	}

	/**
	 * 从请求中获得根域名，形如:www.dress.com
	 */
	public static String getRootDoamin(HttpServletRequest request) {
		// 返回变量
		String doamin = "";
		// 定义临时变量
		String serverName = "";
		int serverNameLength = 0;
		// 获得域名
		serverName = request.getServerName();
		serverName = (serverName != null) ? serverName : "";
		serverNameLength = serverName.length();
		if (serverNameLength > 0) {
			int pos;
			pos = serverName.indexOf(".");
			if (pos > 0) {
				doamin = serverName.substring(pos, serverNameLength);
			}
		}
		// 返回
		return doamin;
	}
	 
	 
	 /** 从请求中获得端口，形如:80
	  */
	public static int getPort(HttpServletRequest request) {
		// 返回变量
		int serverPort;
		// 端口
		serverPort = request.getServerPort();
		// 返回
		return serverPort;
	}

	/**
	 * 从请求中获得请求前缀，形如:www.dress.com:80
	 */
	public static String getUrlPrefix(HttpServletRequest request) {
		// 返回变量
		String urlPrefix = "";
		// 定义临时变量
		String serverName = "";
		int serverPort = 0;
		String joinSybol = ":";
		// 请求前缀
		serverName = getRootDoamin(request);
		serverPort = getPort(request);
		urlPrefix = serverName + joinSybol + serverPort;
		// 返回
		return urlPrefix;
	}

	/**
	 * 从请求中获得请求上下文路径,形如：/
	 */
	public static String getContextPath(HttpServletRequest requqest) {
		// 定义变量
		String contentPath = "";
		contentPath = requqest.getContextPath();
		// 返回
		return contentPath;
	}
	
	 

	/**
	 * 从请求中获得请求上下文路径,形如：/
	 */
	public static String getPath(HttpServletRequest requqest) {
		// 定义变量
		String url = "";
		// 定义临时变量
		String urlPrefix = "";
		String contextPath = "";
		urlPrefix = getUrlPrefix(requqest);
		contextPath = requqest.getContextPath();
		// 返回
		url = urlPrefix + contextPath;
		return url;
	}

	/**
     * 获取访问者IP
     * 
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     * 
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request .getRemoteAddr()。
     * 
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmptyOrNull(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmptyOrNull(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

}
